import request from '@/utils/request'
import type {
  RoleDTO,
  RoleQueryRequest,
  PageResponse,
  ApiResponse
} from '@/types/api'

// 角色管理API
export const roleApi = {
  // 创建角色
  createRole: (data: RoleDTO): Promise<ApiResponse<RoleDTO>> => {
    return request.post('/roles', data)
  },

  // 更新角色信息
  updateRole: (roleId: string, data: RoleDTO): Promise<ApiResponse<RoleDTO>> => {
    return request.put(`/roles/${roleId}`, data)
  },

  // 获取角色详情
  getRole: (roleId: string): Promise<ApiResponse<RoleDTO>> => {
    return request.get(`/roles/${roleId}`)
  },

  // 删除角色
  deleteRole: (roleId: string): Promise<ApiResponse<void>> => {
    return request.delete(`/roles/${roleId}`)
  },

  // 分页查询角色
  queryRoles: (params: RoleQueryRequest): Promise<ApiResponse<PageResponse<RoleDTO>>> => {
    return request.get('/roles', { params })
  },

  // 获取所有角色
  getAllRoles: (): Promise<ApiResponse<RoleDTO[]>> => {
    return request.get('/roles/all')
  },

  // 分配角色权限
  assignPermissions: (roleId: string, permissionIds: string[]): Promise<ApiResponse<void>> => {
    return request.post(`/roles/${roleId}/permissions`, permissionIds)
  },

  // 获取角色权限
  getRolePermissions: (roleId: string): Promise<ApiResponse<string[]>> => {
    return request.get(`/roles/${roleId}/permissions`)
  },

  // 获取角色用户列表
  getRoleUsers: (roleId: string): Promise<ApiResponse<Array<{
    userId: string
    username: string
    nickname?: string
    deptId?: string
    status: number
    isLocked: boolean
    lastLoginTime?: string
  }>>> => {
    return request.get(`/roles/${roleId}/users`)
  },

  // 分配角色菜单
  assignMenus: (roleId: string, menuIds: string[]): Promise<ApiResponse<void>> => {
    return request.post(`/roles/${roleId}/menus`, menuIds)
  },

  // 获取角色菜单
  getRoleMenus: (roleId: string): Promise<ApiResponse<string[]>> => {
    return request.get(`/roles/${roleId}/menus`)
  },

  // 获取角色统计信息
  getRoleStatistics: (): Promise<ApiResponse<{
    totalRoles: number
    enabledRoles: number
    disabledRoles: number
    rolesWithUsers: number
    rolesWithPermissions: number
    averagePermissionsPerRole: number
    averageUsersPerRole: number
  }>> => {
    return request.get('/roles/statistics')
  }
}

export default roleApi
